﻿--[[	$Id: pixelPerfect.lua 3515 2013-08-22 18:30:23Z sdkyron@gmail.com $	]]

local _, caelLib = ...

caelLib.eventFrame = CreateFrame("Frame", nil, UIParent)

local eventFrame = caelLib.eventFrame

eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("UPDATE_FLOATING_CHAT_WINDOWS")

local ScaleFix

eventFrame:SetScript("OnEvent", function(self, event, ...)
	if type(self[event]) == "function" then
		return self[event](self, event, ...)
	end
end)

local Scale = function(value)
    return ScaleFix * math.floor(value / ScaleFix + 0.5)
end

caelLib.scale = function(value) return Scale(value) end

eventFrame.ADDON_LOADED = function(self, event, addon)
	if addon ~= "caelLib" then
		return
	end

	if not caelLibDB then
		caelLibDB  = {}
	end

	local UIScale = caelLibDB.scale or caelLib.scales[screenWidth] and caelLib.scales[screenWidth][screenHeight] or min(2, max(0.64, 768/string.match(caelLib.resolution, "%d+x(%d+)")))

	ScaleFix = (768/tonumber(caelLib.resolution:match("%d+x(%d+)"))) / UIScale

	self:UnregisterEvent(event)
end

eventFrame.UPDATE_FLOATING_CHAT_WINDOWS = function(self, event)
	caelLibDB.scale = floor(GetCVar("uiScale") * 100 + 0.5)/100
end